﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;

namespace BYManageInfoSystem
{
    public partial class Frm_FacMakeInvoiceDetailUnSplit : Form
    {
        private DGBY.BLL.BYCompanyTab m_bllBYCompanyTab = new DGBY.BLL.BYCompanyTab();
        private DGBY.BLL.FactoryDataTab m_bllFactoryDataTab = new DGBY.BLL.FactoryDataTab();
        private DGBY.BLL.FacMakeInvoiceTab m_bllFacMakeInvoiceTab = new DGBY.BLL.FacMakeInvoiceTab();
        private DGBY.BLL.FacMakeInvoiceSplitTab m_bllFacMakeInvoiceSplitTab = new DGBY.BLL.FacMakeInvoiceSplitTab();
        private DGBY.BLL.ValueAddedTaxInvoiceTab m_bllValueAddedTaxInvoiceTab = new DGBY.BLL.ValueAddedTaxInvoiceTab();

        private int m_nSelectFacMakeInvoiceTabID = 0;
        private DateTime m_dtSBDate = new DateTime();

        public class GoodsInfo
        {
            public Decimal dKaiPiaoTotalPrice = 0;
            public long lSeq = 0;
            public Decimal dHuilv = 0;
            public Decimal dBGJinE = 0;
            public Decimal dFator = 0;
            public Decimal dNotComeBackPart = 0;
            public int nFacMakeInvoiceTabID = 0;
            public int nNum = 0;
        }

        //这是个比较器
        public class GoodsInfoComparer : IComparer<GoodsInfo>
        {
            //实现姓名升序
            public int Compare(GoodsInfo x, GoodsInfo y)
            {
                return (y.dKaiPiaoTotalPrice.CompareTo(x.dKaiPiaoTotalPrice));
            }
        }
        //List<GoodsInfo> m_lstGoodsInfo = new List<GoodsInfo>();
        //Dictionary<string, List<GoodsInfo>> dicContractNo2GoodsInfoLst = new Dictionary<string, List<GoodsInfo>>();

        public class CustomMergedCellEvaluator :Infragistics.Win.UltraWinGrid.IMergedCellEvaluator
        {
            UltraGridColumn m_BaseColumn = null;
            public CustomMergedCellEvaluator(UltraGrid UltraGridTemp) 
            {
                foreach (UltraGridColumn column2 in UltraGridTemp.DisplayLayout.Bands[0].Columns)
                {
                    string str = column2.Header.Caption;
                    if (str == "合同编号")
                    {
                        m_BaseColumn = column2;
                        break;
                    }
                }
            }
            // 合并日期相同的单元格（无需时间精确相同）
            public bool ShouldCellsBeMerged(UltraGridRow row1, UltraGridRow row2, UltraGridColumn column)
            {
                string str1 = (string)row1.GetCellValue(m_BaseColumn);
                string str2 = (string)row2.GetCellValue(m_BaseColumn);
                return str1 == str2;

            }

        }

        public Frm_FacMakeInvoiceDetailUnSplit()
        {
            InitializeComponent();
        }

        public void InitUltraWinGridSetting()
        {
            this.ultraGrid1.DisplayLayout.Override.RowSelectors = Infragistics.Win.DefaultableBoolean.True;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorNumberStyle = Infragistics.Win.UltraWinGrid.RowSelectorNumberStyle.VisibleIndex;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorWidth = 40;
        }

        public void LocalPrintPreveiw()
        {
            Infragistics.Shared.ResourceCustomizer rc = Infragistics.Win.Printing.Resources.Customizer;//Resources.Customizer;
            rc.SetCustomizedString("PrintPreview_DialogCaption", "打印预览");
            rc.SetCustomizedString("PrintPreview_Tool_Print", "打印(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_ClosePreview", "关闭(&C)");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuPreviewZoom", "显示比例");
            rc.SetCustomizedString("PrintPreview_Tool_Current_Page", "当前页");
            rc.SetCustomizedString("PrintPreview_Tool_Exit", "退出(&X)");
            rc.SetCustomizedString("PrintPreview_Tool_First_Page", "第一页");
            rc.SetCustomizedString("PrintPreview_Tool_Go_To", "跳至");
            rc.SetCustomizedString("PrintPreview_Tool_Last_Page", "最后一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_Page", "下一页");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_Page", "前一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_View", "下一视图(&N)");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_View", "前一视图(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_Hand_Tool", "手型工具(&H)");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Setup", "页面设置(&U)");
            rc.SetCustomizedString("PrintPreview_Tool_Snapshot_Tool", "快照工具(&S)");
            rc.SetCustomizedString("PrintPreview_Tool_View", "视图(&V)");
            rc.SetCustomizedString("PrintPreview_Tool_Whole_Page", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom", "缩放(&Z)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In", "放大");

            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out", "缩小");

            rc.SetCustomizedString("PrintPreview_ToolCategory_Context_Menus", "上下文菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_File", "文件");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Menus", "菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Tools", "工具栏");
            rc.SetCustomizedString("PrintPreview_ToolCategory_View", "视图");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Zoom_Mode", "缩放模式");

            rc.SetCustomizedString("PrintPreview_ToolTip_ClosePreview", "关闭");
            rc.SetCustomizedString("PrintPreview_ToolTip_Zoom", "缩放");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "页:{0}/{1}");

            rc.SetCustomizedString("CustomizeImg_ToolBar_MenuBar", "菜单");
            rc.SetCustomizedString("CustomizeImg_ToolBar_Standard", "标准");
            rc.SetCustomizedString("CustomizeImg_ToolBar_View", "视图");
            rc.SetCustomizedString("PrintPreview_Tool_File", "文件(&F)");
            rc.SetCustomizedString("PrintPreview_Tool_Tools", "工具(&T)");
            rc.SetCustomizedString("PrintPreview_Tool_Dynamic_Zoom_Tool", "动态缩放工具(&D)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out_Tool", "缩小工具");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In_Tool", "放大工具");
            // rc.SetCustomizedString("PrintPreview_Tool_Page_Layout","菜单");
            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PreviewRowColSelection_SelectedPages", "{0} x {1} 页");

            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Width", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_MarginWidth", "文字宽度");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_PageWidth", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_WholePage", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Layout", "页面布局");
            rc.SetCustomizedString("PrintPreview_Tool_Margin_Width", "文字宽度");
            rc.SetCustomizedString("ContextMenuPreviewHand", "缩放视图");


            rc.SetCustomizedString("PrintPreview_Tool_Reduce_Page_Thumbnails", "缩小");
            rc.SetCustomizedString("PrintPreview_Tool_Show_Page_Numbers", "显示页号");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuThumbnail", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Enlarge_Page_Thumbnails", "放大");
            rc.SetCustomizedString("PrintPreview_Tool_Thumbnails", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Continuous", "连续排序");
            //说明
            rc.SetCustomizedString("StatusBar_DynamicZoom_Instructions", "单击并拖动进行缩放操作");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "当前页: {0} / {1}");
            rc.SetCustomizedString("StatusBar_SnapShot_Instructions", "单击并拖动,系统将选定矩型区域复制到剪帖板");
            rc.SetCustomizedString("StatusBar_ZoomIn_Instructions", "单击并拖动,系统将放大选定矩型区域");
            rc.SetCustomizedString("StatusBar_ZoomOut_Instructions", "单击并拖动,系统将缩小选定矩型区域");
            rc.SetCustomizedString("StatusBar_Hand_Instructions", "单击并拖动以便显示更多内容");
        }

        private void InitCombox()
        {
            DataSet ds = m_bllBYCompanyTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                this.comboBox2Comp.DataSource = ds.Tables[0];
                this.comboBox2Comp.DisplayMember = "经营单位名称";
                this.comboBox2Comp.ValueMember = "BYCompanyTabID";
                this.comboBox2Comp.SelectedIndex = 0;
            }

            ds = m_bllFactoryDataTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                this.comboBoxFac.DataSource = ds.Tables[0];

                this.comboBoxFac.ValueMember = "FactoryDataTabID";
                this.comboBoxFac.DisplayMember = "工厂名称";
                this.comboBoxFac.SelectedIndex = 0;
            }
        }

        private void Frm_FacMakeInvoiceDetailUnSplit_Load(object sender, EventArgs e)
        {
            InitCombox();
            LocalPrintPreveiw();
            InitUltraWinGridSetting();
        }
        void ConvertStringToMultiLineFirst()
        {
            foreach (UltraGridColumn column2 in ultraGrid1.DisplayLayout.Bands[0].Columns)
            {
                string str = column2.Header.Caption;
                if (str == "集装箱柜号")
                {
                    int nRowsCount = this.ultraGrid1.Rows.Count;
                    for (int i = 0; i < nRowsCount; i++)
                    {
                        string strSource = this.ultraGrid1.Rows[i].GetCellValue(column2).ToString();
                        ConvertStringToMultiLineSecond(strSource, i);
                    }
                }
            }
        }

        private void ConvertStringToMultiLineSecond(string strSource, int nRowIndex)
        {
            string str = strSource.ToString();
            string[] arr = str.Split(',');
            string tempa = "";
            int n = 0;
            foreach (string ch in arr)
            {

                if (ch != "")
                {
                    if (n == 0)
                        tempa += ch;
                    else
                        tempa += "\n" + ch;
                }

                n++;
            }

            this.ultraGrid1.Rows[nRowIndex].Cells["集装箱柜号"].Value = tempa;
        }

        private long GetNextSeq()
        {
            DataSet ds = m_bllFacMakeInvoiceSplitTab.GetSeqCount();
            string strSeqCount = ds.Tables[0].Rows[0][0].ToString();
            long nNum = Convert.ToInt64(strSeqCount, 10);
            if(nNum != 0)
            {
                ds = m_bllFacMakeInvoiceSplitTab.GetMaxSeq();
                string strSeqMax = ds.Tables[0].Rows[0][0].ToString();
                nNum = Convert.ToInt64(strSeqMax, 10);
                nNum++;
                return nNum;
            }
            else
            {
                return 1;
            }
            
        }

        private void UpdateOneSplitTabRecord(GoodsInfo giTemp)
        {
            DGBY.Model.FacMakeInvoiceTab modelFacMakeInvoiceTab = m_bllFacMakeInvoiceTab.GetModel(giTemp.nFacMakeInvoiceTabID);
            DGBY.Model.FacMakeInvoiceSplitTab modelFacMakeInvoiceSplitTab = new DGBY.Model.FacMakeInvoiceSplitTab();
            modelFacMakeInvoiceSplitTab.BGDComeBackGoodsMXTabID = modelFacMakeInvoiceTab.BGDComeBackGoodsMXTabID;
            modelFacMakeInvoiceSplitTab.FactorA = modelFacMakeInvoiceTab.FactorA;
            modelFacMakeInvoiceSplitTab.HuiLv = modelFacMakeInvoiceTab.HuiLv;
            modelFacMakeInvoiceSplitTab.TuiShuiLv = modelFacMakeInvoiceTab.TuiShuiLv;
            modelFacMakeInvoiceSplitTab.FactorB = modelFacMakeInvoiceTab.FactorB;
            modelFacMakeInvoiceSplitTab.KaiPiaoDeadLine = modelFacMakeInvoiceTab.KaiPiaoDeadLine;
            Decimal dSeagateJinE = giTemp.dBGJinE;

            modelFacMakeInvoiceSplitTab.BGJinE = dSeagateJinE;
            modelFacMakeInvoiceSplitTab.PriceWithTax = dSeagateJinE
                                                * (modelFacMakeInvoiceSplitTab.HuiLv - modelFacMakeInvoiceSplitTab.FactorA) * (Decimal)1.17 / modelFacMakeInvoiceSplitTab.FactorB;

            modelFacMakeInvoiceSplitTab.KaiPiaoTotalPrice = dSeagateJinE * (modelFacMakeInvoiceSplitTab.HuiLv - modelFacMakeInvoiceSplitTab.FactorA) / modelFacMakeInvoiceSplitTab.FactorB;
            modelFacMakeInvoiceSplitTab.BackTaxMoney = modelFacMakeInvoiceSplitTab.KaiPiaoTotalPrice * modelFacMakeInvoiceSplitTab.TuiShuiLv;
            modelFacMakeInvoiceSplitTab.SellPrice = dSeagateJinE * modelFacMakeInvoiceSplitTab.HuiLv;
            modelFacMakeInvoiceSplitTab.PrimeCost = modelFacMakeInvoiceSplitTab.FactorB * modelFacMakeInvoiceSplitTab.KaiPiaoTotalPrice;
            modelFacMakeInvoiceSplitTab.Profit = modelFacMakeInvoiceSplitTab.SellPrice - modelFacMakeInvoiceSplitTab.PrimeCost;
            modelFacMakeInvoiceSplitTab.Rate = modelFacMakeInvoiceSplitTab.Profit / modelFacMakeInvoiceSplitTab.SellPrice;

            modelFacMakeInvoiceSplitTab.SeqNo = giTemp.lSeq;
            modelFacMakeInvoiceSplitTab.FPieceNum = giTemp.nNum;
            m_bllFacMakeInvoiceSplitTab.Update(modelFacMakeInvoiceSplitTab);
        }

        private void AddOneSplitTabRecord(GoodsInfo giTemp)
        {
            DGBY.Model.FacMakeInvoiceTab modelFacMakeInvoiceTab = m_bllFacMakeInvoiceTab.GetModel(giTemp.nFacMakeInvoiceTabID);
            DGBY.Model.FacMakeInvoiceSplitTab modelFacMakeInvoiceSplitTab = new DGBY.Model.FacMakeInvoiceSplitTab();
            modelFacMakeInvoiceSplitTab.BGDComeBackGoodsMXTabID = modelFacMakeInvoiceTab.BGDComeBackGoodsMXTabID;
            modelFacMakeInvoiceSplitTab.FactorA = modelFacMakeInvoiceTab.FactorA;
            modelFacMakeInvoiceSplitTab.HuiLv = modelFacMakeInvoiceTab.HuiLv;
            modelFacMakeInvoiceSplitTab.TuiShuiLv = modelFacMakeInvoiceTab.TuiShuiLv;
            modelFacMakeInvoiceSplitTab.FactorB = modelFacMakeInvoiceTab.FactorB;
            modelFacMakeInvoiceSplitTab.KaiPiaoDeadLine = modelFacMakeInvoiceTab.KaiPiaoDeadLine;
            Decimal dSeagateJinE = giTemp.dBGJinE;

            modelFacMakeInvoiceSplitTab.BGJinE = dSeagateJinE;
            modelFacMakeInvoiceSplitTab.PriceWithTax = dSeagateJinE
                                                * (modelFacMakeInvoiceSplitTab.HuiLv - modelFacMakeInvoiceSplitTab.FactorA) * (Decimal)1.17 / modelFacMakeInvoiceSplitTab.FactorB;

            modelFacMakeInvoiceSplitTab.KaiPiaoTotalPrice = dSeagateJinE * (modelFacMakeInvoiceSplitTab.HuiLv - modelFacMakeInvoiceSplitTab.FactorA) / modelFacMakeInvoiceSplitTab.FactorB;
            modelFacMakeInvoiceSplitTab.BackTaxMoney = modelFacMakeInvoiceSplitTab.KaiPiaoTotalPrice * modelFacMakeInvoiceSplitTab.TuiShuiLv;
            modelFacMakeInvoiceSplitTab.SellPrice = dSeagateJinE * modelFacMakeInvoiceSplitTab.HuiLv;
            modelFacMakeInvoiceSplitTab.PrimeCost = modelFacMakeInvoiceSplitTab.FactorB * modelFacMakeInvoiceSplitTab.KaiPiaoTotalPrice;
            modelFacMakeInvoiceSplitTab.Profit = modelFacMakeInvoiceSplitTab.SellPrice - modelFacMakeInvoiceSplitTab.PrimeCost;
            modelFacMakeInvoiceSplitTab.Rate = modelFacMakeInvoiceSplitTab.Profit / modelFacMakeInvoiceSplitTab.SellPrice;

            modelFacMakeInvoiceSplitTab.SeqNo = giTemp.lSeq;
            modelFacMakeInvoiceSplitTab.FPieceNum = giTemp.nNum;
            int nFacMakeInvoiceSplitTabID =  m_bllFacMakeInvoiceSplitTab.Add(modelFacMakeInvoiceSplitTab);

            DataSet ds = m_bllValueAddedTaxInvoiceTab.GetValueAddedTaxInvoiceListAbbr("dbo.FacMakeInvoiceSplitTab.SeqNo = '" + giTemp.lSeq.ToString() + "'");

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return;
            }

            DGBY.Model.ValueAddedTaxInvoiceTab modelValueAddedTaxInvoiceTab = new DGBY.Model.ValueAddedTaxInvoiceTab();
            modelValueAddedTaxInvoiceTab.FacMakeInvoiceSplitTabID = nFacMakeInvoiceSplitTabID;
            modelValueAddedTaxInvoiceTab.TakeInvoiceDate = System.DateTime.Now;
            modelValueAddedTaxInvoiceTab.BackTaxDate = System.DateTime.Now;
            m_bllValueAddedTaxInvoiceTab.Add(modelValueAddedTaxInvoiceTab);

            
        }
    

        private void SplitRecord(int nBGDComeBackGoodsMXTabID, string strWhere)
        {
            List<GoodsInfo> lstGoodsInfo = new List<GoodsInfo>();
            DataSet ds = m_bllFacMakeInvoiceTab.GetFacMakeInvoiceList("FacMakeInvoiceTab.BGDComeBackGoodsMXTabID = '" + nBGDComeBackGoodsMXTabID.ToString() + "'");
            string strContractNoTemp = ds.Tables[0].Rows[0]["合同编号"].ToString();
            ds = m_bllFacMakeInvoiceTab.GetFacMakeInvoiceList("PaidanRegisterTab.ContractCode = '" + strContractNoTemp + "'");

            DataSet ds2 = m_bllFacMakeInvoiceSplitTab.GetFacMakeInvoiceSplitList("PaidanRegisterTab.ContractCode = '" + strContractNoTemp + "'");
            //删除之前拆分的结果
            if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
                {
                    string strFacMakeInvoiceSplitTabID = ds2.Tables[0].Rows[i]["FacMakeInvoiceSplitTabID"].ToString();
                    int nFacMakeInvoiceSplitTabID = Convert.ToInt32(strFacMakeInvoiceSplitTabID, 10);
                    m_bllFacMakeInvoiceSplitTab.Delete(nFacMakeInvoiceSplitTabID);
                }
            }


            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                //填充lstGoodsInfo
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strContractNo = ds.Tables[0].Rows[i]["合同编号"].ToString();

                    string strBGDComeBackGoodsMXTabID = ds.Tables[0].Rows[i]["BGDComeBackGoodsMXTabID"].ToString();

                    string strName = ds.Tables[0].Rows[i]["开票总价"].ToString();
                    Decimal dTotal = Convert.ToDecimal(strName);
                    if (dTotal < (Decimal)0.000001)
                        continue;
                    strName = ds.Tables[0].Rows[i]["报关金额"].ToString();
                    Decimal dBGJinE = Convert.ToDecimal(strName);
                    strName = ds.Tables[0].Rows[i]["汇率"].ToString();
                    Decimal dHuilv = Convert.ToDecimal(strName);
                    strName = ds.Tables[0].Rows[i]["系数A"].ToString();
                    Decimal dNotComeBackPart = Convert.ToDecimal(strName);
                    strName = ds.Tables[0].Rows[i]["系数B"].ToString();
                    Decimal dFator = Convert.ToDecimal(strName);
                    strName = ds.Tables[0].Rows[i]["数量"].ToString();
                    int nNum = Convert.ToInt32(strName, 10);
                    string strFacMakeInvoiceTabID = ds.Tables[0].Rows[i]["FacMakeInvoiceTabID"].ToString();
                    int nFacMakeInvoiceTabID = Convert.ToInt32(strFacMakeInvoiceTabID, 10);

                    GoodsInfo giTemp = new GoodsInfo();
                    giTemp.dKaiPiaoTotalPrice = dTotal;
                    giTemp.nFacMakeInvoiceTabID = nFacMakeInvoiceTabID;
                    giTemp.dHuilv = dHuilv;
                    giTemp.dNotComeBackPart = dNotComeBackPart;
                    giTemp.dBGJinE = dBGJinE;
                    giTemp.dFator = dFator;
                    giTemp.nNum = nNum;
                    lstGoodsInfo.Add(giTemp);
                    lstGoodsInfo.Sort(new GoodsInfoComparer());//从大到小
                }

                List<GoodsInfo> newlstTemp = new List<GoodsInfo>();
                //首先拆分
                foreach (GoodsInfo giTemp in lstGoodsInfo)
                {
                    if (giTemp.dKaiPiaoTotalPrice > (Decimal)99999.99)
                    {
                        Decimal dSingleCost = giTemp.dBGJinE / giTemp.nNum;
                        Decimal dMaxBGJinE = (Decimal)((Decimal)99999.99 * giTemp.dFator / (giTemp.dHuilv - giTemp.dNotComeBackPart));
                        int nNewNum = (int)(dMaxBGJinE / dSingleCost);//拆分后的每组数量，比如9，则9+9+9+5 = 32
                        int nTempNum = giTemp.nNum;//总数量，比如32
                        long nOriginalSeq = giTemp.lSeq;
                        while (nTempNum > 0)
                        {
                            GoodsInfo giTemp2 = giTemp;
                            giTemp2.lSeq = nOriginalSeq;


                            if (nTempNum > nNewNum)
                            {
                                giTemp2.nNum = nNewNum;
                                giTemp2.dBGJinE = giTemp2.nNum * dSingleCost;
                                giTemp2.dKaiPiaoTotalPrice = giTemp2.dBGJinE * (giTemp2.dHuilv - giTemp2.dNotComeBackPart) * (Decimal)1.17 / giTemp2.dFator;
                                giTemp2.lSeq = GetNextSeq();
                                AddOneSplitTabRecord(giTemp2);
                            }
                            else
                            {
                                giTemp2.nNum = nTempNum;
                                giTemp2.dBGJinE = giTemp2.nNum * dSingleCost;
                                giTemp2.dKaiPiaoTotalPrice = giTemp2.dBGJinE * (giTemp2.dHuilv - giTemp2.dNotComeBackPart) * (Decimal)1.17 / giTemp2.dFator;
                                newlstTemp.Add(giTemp2);
                            }
                            nTempNum -= nNewNum;
                        }


                    }
                    else
                    {
                        newlstTemp.Add(giTemp);
                    }
                }

                newlstTemp.Sort(new GoodsInfoComparer());
                //接下来合并
                List<GoodsInfo> newlstTemp2 = new List<GoodsInfo>();
                long lSeq = GetNextSeq();
                Decimal dTotals = 0;
                foreach (GoodsInfo giTemp in newlstTemp)
                {
                    GoodsInfo giTemp2 = giTemp;
                    dTotals += giTemp.dKaiPiaoTotalPrice;
                    if (dTotals > (Decimal)99999.99)
                    {
                        lSeq++;
                        giTemp2.lSeq = lSeq;
                        dTotals = giTemp.dKaiPiaoTotalPrice;
                    }
                    else
                    {
                        giTemp2.lSeq = lSeq;
                    }

                    AddOneSplitTabRecord(giTemp2);
                }

            }
        }

        private void ShowAllRecord(string strWhere)
        {
            //dicContractNo2GoodsInfoLst.Clear();
            DataSet ds = m_bllFacMakeInvoiceTab.GetFacMakeInvoiceList(strWhere);

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                ultraGrid1.DataSource = ds.Tables[0];
                this.ultraGrid1.DisplayLayout.Bands[0].Columns["集装箱柜号"].CellMultiLine = Infragistics.Win.DefaultableBoolean.True;
                //ConvertStringToMultiLineFirst();
                ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
                ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
            }
        }

        private void buttonQuery_Click(object sender, EventArgs e)
        {
            ShowAllRecord(@"PaidanRegisterTab.BYCompanyTabID = '" + this.comboBox2Comp.SelectedValue + "'"
                                                                           + " and FacConPeoAndTelTab.FactoryDataTabID = '" + this.comboBoxFac.SelectedValue + "'"
                                                                           + " and BGDComeBackTab.SBDate >= '" + this.dateTimePickerFrom.Value + "'" + " and BGDComeBackTab.SBDate <= '" + this.dateTimePickerTo.Value + "'");
            

        }

        private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            ultraGrid1.DisplayLayout.Bands[0].UseRowLayout = true;
            ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
                ugc.PerformAutoResize();

        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
                ugc.Width++;
            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }

        private void ultraGrid1_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextVAlign = VAlign.Middle;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextVAlign = VAlign.Middle;

            ultraGrid1.DisplayLayout.Bands[0].Columns["合同编号"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["申报日期"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["报关单号"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["集装箱柜号"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["最后开票日期"].MergedCellStyle = MergedCellStyle.Always;

            ultraGrid1.DisplayLayout.Bands[0].Columns["合同编号"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["申报日期"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["报关单号"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["集装箱柜号"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["最后开票日期"].MergedCellEvaluator = new
CustomMergedCellEvaluator(this.ultraGrid1);
        }

        private void ultraGridExcelExporter1_CellExported(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.CellExportedEventArgs e)
        {
            // Get the cell being exporter
            UltraGridCell cell = e.GridRow.Cells[e.GridColumn];

            // Get the Merged cells. 
            UltraGridCell[] mergedCells = cell.GetMergedCells();
            

            // Check to see if there are any merged cells. If not, we don't need to do anything. 
            if (mergedCells != null)
            {
                // There are merged cells. Check to see if the cell being exported is the first one. 
                bool isFirstCell = true;
                foreach (UltraGridCell mergedCell in mergedCells)
                {
                    if (cell.Row.Index > mergedCell.Row.Index)
                    {
                        // If the cell being exported has a higher index that any of the cells
                        // it is merged with, them it's not the first cell and we should already
                        // have handled the merge. 
                        isFirstCell = false;
                        break;
                    }
                }

                // If it is the first cell, merge this cell with the cells below it based on the 
                // count of the merged cells. 
                if (isFirstCell)
                {
                    int rowIndex = e.CurrentRowIndex;
                    int colIndex = e.CurrentColumnIndex;
                    Infragistics.Excel.WorksheetMergedCellsRegion mergedRegion = e.CurrentWorksheet.MergedCellsRegions.Add(
                        rowIndex,
                        colIndex,
                        rowIndex + (mergedCells.Length -1),
                        colIndex);
                    mergedRegion.CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
                    mergedRegion.CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;
                }

            }
        }

        private bool IsDecimal(string strInput)
        {
            bool bRet = Regex.IsMatch(strInput, @"([1-9]+[0-9]*(\.[0-9]+))|(0(\.[0-9]+))");
            return bRet;
        }

        private bool IsNum(string strInput)
        {
            bool bRet = Regex.IsMatch(strInput, @"^[1-9]+\d*$");
            return bRet;
        }

        private bool ValidDate(string strInput)
        {
            if (strInput.Length != 8)
                return false;
            else
                return IsNum(strInput);
        }

        public bool IsDecimal(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else if (!IsDecimal(TextBox.Text) && !IsNum(TextBox.Text))
            {
                errorProvider1.SetError(TextBox, "必须输入数字");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }

        public bool IsNum(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else if (!IsNum(TextBox.Text))
            {
                errorProvider1.SetError(TextBox, "必须输入数字");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }

        public bool IsNull(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }


        private void buttonModify_Click(object sender, EventArgs e)
        {
            try
            {
                DGBY.Model.FacMakeInvoiceTab modelFacMakeInvoiceTabOld = m_bllFacMakeInvoiceTab.GetModel(m_nSelectFacMakeInvoiceTabID);
                if (modelFacMakeInvoiceTabOld == null)
                {
                    MessageBox.Show("数据库不存在该记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                DGBY.Model.FacMakeInvoiceTab modelFacMakeInvoiceTab = new DGBY.Model.FacMakeInvoiceTab();
                modelFacMakeInvoiceTab = modelFacMakeInvoiceTabOld;
                if (ClassInputValid.IsDecimal(this.errorProvider1, this.textBoxUnBackPart))
                    return;
                if (ClassInputValid.IsDecimal(this.errorProvider1, this.textBoxFactorA))
                    return;
                if (ClassInputValid.IsDecimal(this.errorProvider1, this.textBoxHuiLv))
                    return;
                if (ClassInputValid.IsDecimal(this.errorProvider1, this.textBoxBackTaxLv))
                    return;

                modelFacMakeInvoiceTab.FactorA = Convert.ToDecimal(this.textBoxUnBackPart.Text);

                modelFacMakeInvoiceTab.HuiLv = Convert.ToDecimal(this.textBoxHuiLv.Text);
                modelFacMakeInvoiceTab.TuiShuiLv = Convert.ToDecimal(this.textBoxBackTaxLv.Text);
                modelFacMakeInvoiceTab.FactorB = (Decimal)((Decimal)1.17 - modelFacMakeInvoiceTab.TuiShuiLv);
                Decimal dSeagateJinE = Convert.ToDecimal(this.textBoxSeagateJinE.Text);

                //if (modelFacMakeInvoiceTab.TuiShuiLv == 0.17)
                //    modelFacMakeInvoiceTab.FactorB = 1;
                //else if (modelFacMakeInvoiceTab.TuiShuiLv == 0.13)
                //    modelFacMakeInvoiceTab.FactorB = 1.04;
                //else if (modelFacMakeInvoiceTab.TuiShuiLv == 0.11)
                //    modelFacMakeInvoiceTab.FactorB = 1.06;
                //else if (modelFacMakeInvoiceTab.TuiShuiLv == 0.09)
                //    modelFacMakeInvoiceTab.FactorB = 1.08;
                //else if (modelFacMakeInvoiceTab.TuiShuiLv == 0.17)
                //    modelFacMakeInvoiceTab.FactorB = 1;
                //else if (modelFacMakeInvoiceTab.TuiShuiLv == 0.17)
                //    modelFacMakeInvoiceTab.FactorB = 1;


                modelFacMakeInvoiceTab.PriceWithTax = dSeagateJinE
                                                    * (modelFacMakeInvoiceTab.HuiLv - modelFacMakeInvoiceTab.FactorA) * (Decimal)1.17 / modelFacMakeInvoiceTab.FactorB;

                modelFacMakeInvoiceTab.KaiPiaoTotalPrice = dSeagateJinE * (modelFacMakeInvoiceTab.HuiLv - modelFacMakeInvoiceTab.FactorA) / modelFacMakeInvoiceTab.FactorB;
                modelFacMakeInvoiceTab.BackTaxMoney = modelFacMakeInvoiceTab.KaiPiaoTotalPrice * modelFacMakeInvoiceTab.TuiShuiLv;
                modelFacMakeInvoiceTab.SellPrice = dSeagateJinE * modelFacMakeInvoiceTab.HuiLv;
                modelFacMakeInvoiceTab.PrimeCost = modelFacMakeInvoiceTab.FactorB * modelFacMakeInvoiceTab.KaiPiaoTotalPrice;
                modelFacMakeInvoiceTab.Profit = modelFacMakeInvoiceTab.SellPrice - modelFacMakeInvoiceTab.PrimeCost;
                modelFacMakeInvoiceTab.Rate = modelFacMakeInvoiceTab.Profit / modelFacMakeInvoiceTab.SellPrice;
                modelFacMakeInvoiceTab.KaiPiaoDeadLine = (DateTime)m_dtSBDate.AddDays(75);



                m_bllFacMakeInvoiceTab.Update(modelFacMakeInvoiceTab);

                SplitRecord(modelFacMakeInvoiceTab.BGDComeBackGoodsMXTabID, @"PaidanRegisterTab.BYCompanyTabID = '" + this.comboBox2Comp.SelectedValue + "'"
                                                                               + " and FacConPeoAndTelTab.FactoryDataTabID = '" + this.comboBoxFac.SelectedValue + "'"
                                                                               + " and BGDComeBackTab.SBDate >= '" + this.dateTimePickerFrom.Value + "'" + " and BGDComeBackTab.SBDate <= '" + this.dateTimePickerTo.Value + "'");


                ShowAllRecord(@"PaidanRegisterTab.BYCompanyTabID = '" + this.comboBox2Comp.SelectedValue + "'"
                                                                               + " and FacConPeoAndTelTab.FactoryDataTabID = '" + this.comboBoxFac.SelectedValue + "'"
                                                                               + " and BGDComeBackTab.SBDate >= '" + this.dateTimePickerFrom.Value + "'" + " and BGDComeBackTab.SBDate <= '" + this.dateTimePickerTo.Value + "'");


                MessageBox.Show("数据修改成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
           
        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            string strFacMakeInvoiceTabID = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells[0].Text;
            m_nSelectFacMakeInvoiceTabID = Convert.ToInt32(strFacMakeInvoiceTabID, 10);
            cellFacMakeInvoiceTabClick();
        }
     

    
        private void cellFacMakeInvoiceTabClick()
        {
            DGBY.Model.FacMakeInvoiceTab modelFacMakeInvoiceTab = m_bllFacMakeInvoiceTab.GetModel(m_nSelectFacMakeInvoiceTabID);
            if (modelFacMakeInvoiceTab != null)
            {
                this.textBoxContractNo.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["合同编号"].Text;
                this.textBoxBGDNo.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["报关单号"].Text;
                this.textBoxGoodsName.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["商品名称"].Text;
                
                this.textBoxSeqNo.Text = this.ultraGrid1.ActiveCell.Row.Index.ToString();
                this.textBoxWithFaxPrice.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["含税价"].Text;
                this.textBoxMakeInvoiceTotalPrice.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["开票总价"].Text;
                this.textBoxUnit.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["单位"].Text;
                this.textBoxNum.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["数量"].Text;
                this.textBoxGoodsType.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["规格型号质地"].Text;
                this.textBoxSeagateJinE.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["报关金额"].Text;

                this.textBoxCost.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["成本"].Text;
                this.textBoxSellPrice.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["售价"].Text;
                this.textBoxBackTaxJinE.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["应退税金额"].Text;

                this.textBoxBackTaxLv.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["退税率"].Text;
                this.textBoxFactorA.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["系数B"].Text;
                this.textBoxUnBackPart.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["系数A"].Text;

                this.textBoxPercent.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["百分比"].Text;
                this.textBoxProfit.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["利润"].Text;
                this.textBoxHuiLv.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["汇率"].Text;

                //this.textBoxPayMonth.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["付款月份"].Text;

                m_dtSBDate = this.dateTimePickerSBDate.Value = (DateTime)this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["申报日期"].Value;
                this.dateTimePickerDeadlineDate.Value = (DateTime)this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["最后开票日期"].Value;

                //this.comboBoxAbstract.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["摘要"].Text;

            }
        }

        private void ultraGridExcelExporter1_BeginExport(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.BeginExportEventArgs e)
        {
            Worksheet ws = e.CurrentWorksheet;



            ws.Rows[1].Cells[5].Value = this.comboBoxFac.Text + "开票明细";
            ws.Rows[1].Cells[6].Value = DateTime.Now.Date;


            ws.Rows[2].Cells[0].Value = @"注：以下是开给“" + this.comboBox2Comp.Text + @"”";
            e.CurrentRowIndex = 3;
        }

    }
}